<?php
declare(strict_types=1);

namespace Service\UserService;

use Service\BaseService;
use Service\Code\Normal;
use App\Model\BbcModel\Member;
use App\Model\BbcModel\Vip;
use App\Model\BbcModel\ConfigChannel;
use App\Model\BbcModel\ShoppingGuide;
use App\Model\BbcModel\Order;
use App\Model\BbcModel\OrderReturn;
use App\Model\BbcModel\MemberCertification;
use App\Model\BbcModel\MnCheckUser;
use App\Model\BbcModel\StoreRelation;
use App\Model\BbcModel\VipCard;
use App\Model\BbcModel\MemberPointsLog;
use App\Model\BbcModel\GoodsPointsLog;
use App\Model\BbcModel\GoodsPointsConfig;
use Service\VenderClient\Hashids\Application as HashIds;
use Service\HelperService\Common;
use App\Model\BbcModel\OpenId;
use Service\PayService\Payer\Wxmnapp;

/**
 * TO C/B 用户账户
 * @author hj
 */
class AccountService extends BaseService
{    
    /**
     * 评价列表
     * @param int $cid
     * @param int $mnid
     * @param int $mn_sid
     * @param int $mid
     */
    public function memberAccount(int $cid,int $mnid,int $mn_sid,int $mid)
    {
        $fields = [
            'mb.mid', 'mb.account', 'mb.level', 'mb.balance', 'mb.points', 'mb.points_history',
            'mb.pay_password', 'mb.cd', 'mb.goods_points', 'mbf.nickname', 'mbf.avatar', 'mbf.sex',
            'mbf.truename', 'mbf.birthday', 'mbf.guide_id'
        ];
        $member = Member::query()->from((new Member)->getTable() . ' as mb')->join("ly_member_info as mbf", 'mbf.mid', '=', 'mb.mid')
            ->where('mb.mid', $mid)->select($fields)->first();
        if (!$member) {
            return Normal::returnCode(Normal::FAIL, '用户不存在');
        }
        
        //账号信息
        $member                 = $member->toArray();
        $member['points']       = round($member['points'], 2);
        $member['goods_points'] = round($member['goods_points'], 2);
        $member['pay_pass']     = $member['pay_password'] ? 1 : 0;
        unset($member['pay_password']);
        $memberInfo           = [
            'nickname' => $member['nickname'],
            'avatar'   => $member['avatar'],
            'sex'      => $member['sex'],
            'truename' => $member['truename'],
            'birthday' => $member['birthday'],
            'guide_id' => $member['guide_id'],
        ];
        $memberInfo['avatar'] = str_replace("http://appapi.indoorbuy.com/", Common::$pre_image_url, $member['avatar']);
        if (!empty($memberInfo['avatar']) && strpos($memberInfo['avatar'], 'http') === false) {
            $memberInfo['avatar'] = Common::$pre_image_url . $memberInfo['avatar'];
        }
        $member['show_wechat'] = 0;
        
        //黑卡   mnid 2表示B端  4表示C端
        if ( $mnid == TO_C_MNID_TYPE ) 
        {
            $member['is_show_points'] = 0;
            $GoodsPointsStatus        = GoodsPointsConfig::where('cid', $cid)->value('status');
            if (!empty($GoodsPointsStatus)) {
                $member['is_show_points'] = $GoodsPointsStatus;
            }
            $vipCheckRes           = Vip::check(['mn_sid'=>$mn_sid,'mid'=>$mid]);
            $member['is_vip']      = $vipCheckRes['is_vip'];
            $member['expire_time'] = $vipCheckRes['expire_time'] > 0 ? date('Y-m-d H:i:s', $vipCheckRes['expire_time']) : 0;
            //会员充值金额
            $member['vip_price']    = 199;
            $member['show_new_vip'] = 0;
            $configChannel          = ConfigChannel::whereIn('code', ['member_vip_fee', 'wechat_msg_template', 'wxmp_pay'])->where('cid', $cid)->get();
            if ($configChannel->isEmpty()) {
                return Normal::returnCode(Normal::FAIL, '获取渠道配置失败');
            }
            $configChannel = array_column($configChannel->toArray(), null, 'code');
            if (isset($configChannel['member_vip_fee']) && !empty($configChannel['member_vip_fee'])) {
                $value = json_decode($configChannel['member_vip_fee']['value'], true);
                if (isset($value['year_activity']) && $value['year_activity'] != '') {
                    $member['vip_price'] = $value['year_activity'];
                }
                if (!is_numeric($member['vip_price']) || $member['vip_price'] < 0) {
                    $member['vip_price'] = 0;
                }
                if ($member['vip_price'] * 100 != floor($member['vip_price'] * 100)) {
                    $member['vip_price'] = sprintf("%.2f", substr(sprintf("%.3f", $member['vip_price']), 0, -1));
                }
                $gift = $value['gift'] ?? '';
                if (intval($gift) > 0 && ($member['cd'] + 24 * 60 * 60) > time() && $member['is_vip'] == 0) {
                    $member['show_new_vip'] = 1;
                }
            }
            $memberInfo['guide_name'] = '';
            if ($member['guide_id']) {
                $memberInfo['guide_name'] = ShoppingGuide::where('id', $member['guide_id'])->value('name');
            }
            if (isset($configChannel['wechat_msg_template']) && !empty($configChannel['wechat_msg_template']['value'])) {
                $member['show_wechat'] = 1;
            }
            $member['wxmp_qrcode'] = '';
            $wxmp                  = $configChannel['wxmp_pay'];
            if (isset($configChannel['wxmp_pay']) && !empty($configChannel['wxmp_pay']['value'])) {
                $wxmpValue = !empty(json_decode($configChannel['wxmp_pay']['value'])) ? json_decode($configChannel['wxmp_pay']['value'], true) : $configChannel['wxmp_pay']['value'];
                if ($wxmpValue) {
                    $member['wxmp_qrcode'] = $wxmpValue['wxmp_qrcode'];
                }
            }
            $memberInfo['is_guide']     = 0;
            $memberInfo['guide_qrcode'] = '';
            $memberInfo['guide_code']   = '';
            $guide                      = ShoppingGuide::where('mobile', $member['account'])->where('mn_sid', $mn_sid)->first();
            if ($guide) {
                $memberInfo['is_guide']     = 1;
                $memberInfo['guide_qrcode'] = $guide->qrcode;
                $memberInfo['guide_code']   = $guide->code;
            }
        }
        //订单
        $orderNum           = Order::getMemberOrderNum($member['mid'], $mnid, $mn_sid, $cid);
        $orderNum['return'] = OrderReturn::where('mid', $member['mid'])->where('mnid', $mnid)->where('mn_sid', $mn_sid)->where('cid', $cid)->whereIn('check_status', [0, 4])->count();
        //判断是否企业认证
        $isbusiness = MemberCertification::check(['mid' => $member['mid']]);
        //是否通过验证
        $is_check = MnCheckUser::check(['mid' => $mid, 'cid' => $cid]);
        //关联的店铺
        $relationStore = StoreRelation::getStore(['mid' => $mid, 'cid' => $cid]);
        $vip_card      = null;
        $card          = VipCard::where('mid', $mid)->whereRaw('card_num > card_used')->first();
        if ($card) {
            $vip_card['id']         = $card->id;
            $vip_card['card_total'] = $card->card_num;
            $vip_card['card_num']   = bcsub($card->card_num, $card->card_used);
            $vip_card['card_day']   = $card->card_day;
        }
        $bind                = OpenId::where('mid', $member['mid'])->where('tob', 'open_wx_login')->where('cid', $cid)->select(['openid'])->first();
        $member['subscribe'] = 0;
        if (empty($bind) || empty($bind->openid)) {
            $mids = Member::where('account', $member['account'])->where('cid', $cid)->pluck('mid')->toArray();
            $bind = OpenId::whereIn('mid', $mids)->where('tob', 'open_wx_login')->where('openid', '<>', '')->select(['openid'])->first();
        }
        
        if (!empty($bind)) {
            
            //这里还需要修改//获取订阅信息
            $subscribe = Wxmnapp::instance()->getSubscribe($cid, $mn_sid, $mnid, $bind->openid);
            if ($subscribe['code'] == Normal::SUC) {
                $member['subscribe'] = $subscribe['data']['subscribe'];
            }
        }
        
        $member['account'] = hide_mobile($member['account']);
        $member['mid']     = HashIds::instance()->encode($mid);
        unset($member['nickname'],$member['avatar'],$member['sex'],$member['truename'],$member['birthday'],$member['guide_id']);
        //账户信息
        $data = [
            'account'       => $member,
            'info'          => $memberInfo,
            'order'         => $orderNum,
            'is_auth'       => 0,
            'is_business'   => $isbusiness['data']['isCheck'],
            'is_check'      => $is_check,
            'relationStore' => $relationStore,
            'vip_card'      => $vip_card,
        ];
        return Normal::returnCode(Normal::SUC, '获取成功', $data);
    }
    
    /**
     * 积分明细-已废弃
     * @param array $param 包含了系统默认参数
     * @author: hj
     * @param int $cid
     * @param int $mnid
     * @param int $mn_sid
     * @param int $mid
     * @param array $param
     */
    public function pointsLog(int $cid,int $mnid,int $mn_sid,int $mid,array $param)
    {
        $fields = ['symbol', 'points', 'remark', 'cd',];
        $model = MemberPointsLog::where('mid', (int)($mid))->select($fields);
        if(isset($param['page']) && ctype_digit((string)$param['page']) && $param['page'] > 0){
            $this->page = $param['page'];
        }
        if(isset($param['limit']) && ctype_digit((string)$param['limit']) && $param['limit'] > 0){
            $this->limit = $param['limit'];
        }
        $result = $model->orderBy('id', 'desc')->paginate($this->limit, ['*'], 'page', $this->page);
        if($result->isEmpty()){
            return Normal::returnCode(Normal::SUC, '获取成功');
        }
        $result->each(function ($item, $key) {
            $item->date = date('Y-m-d', $item['cd']);
            $item->symbol = MemberPointsLog::$symbol[$item['symbol']] ?? '';
            return $item;
        });
        return Normal::returnCode(Normal::SUC, '获取成功', $result->items());
    }
    
    /**
     * 新积分明细
     * @param array $param 包含了系统默认参数
     * @author: hj
     * @param int $cid
     * @param int $mnid
     * @param int $mn_sid
     * @param int $mid
     * @param array $param
     * @return mixed
     */
    public function goodsPointsLog(int $cid,int $mnid,int $mn_sid,int $mid,array $param)
    {
        $model = GoodsPointsLog::where('mid',$mid);
        if(isset($param['page']) && ctype_digit((string)$param['page']) && $param['page'] > 0){
            $this->page = $param['page'];
        }
        if(isset($param['limit']) && ctype_digit((string)$param['limit']) && $param['limit'] > 0){
            $this->limit = $param['limit'];
        }
        if(isset($param['type']) && in_array($param['type'], ['0', '1'])){
            $model = $model->where('type', $param['type']);
        }
        $result = $model->orderBy('id', 'desc')->paginate($this->limit, ['*'], 'page', $this->page);
        if($result->isEmpty()){
            return Normal::returnCode(Normal::SUC, '获取成功');
        }
        $result->each(function ($item, $key) {
            $item->cd = date('Y-m-d H:i:s', $item['cd']);
            return $item;
        });
        return Normal::returnCode(Normal::SUC, '获取成功', $result->items());
    }

    /**
     * 新积分规则
     * @param array $param 包含了系统默认参数
     * @author: hj
     * @param int $cid
     * @param int $mnid
     * @param int $mn_sid
     * @param int $mid
     * @param array $param
     * @return int[]|string[]|array[]
     */
    public function pointsRule(int $cid,int $mnid,int $mn_sid,int $mid,array $param)
    {
        $param['cid'] = $cid;
        return GoodsPointsConfig::getRule($param);
    }
}